<template>
	<div class="Coupons2">
		<div style="text-align: left;"><span>组件名称：</span>自定义图片优惠券组件</div>
		<blue-button text="新增" :clickEvent="clickAdd" style="text-align: left;"></blue-button>
		<div class="bannerstyle">
			<span>优惠券展示样式：</span>
			<div class="banneranim" v-for="(item, index) in SelectedStatedata" :key="index">
				<cirle-select class="stylename" :state="item.index == activeIndex" :clickEvent="CirleSelectedState.bind(this, item.index)"></cirle-select><span>{{item.text}}</span>
			</div>
		</div>
		<table class="sv-table">
			<tr class="table-th">
				<th>资源位</th>
				<th>资源图片</th>
				<th>活动名称</th>
				<th>活动编码</th>
				<th>优惠券名称</th>
				<th>优惠券编码</th>
				<th>更新日期</th>
				<th>操作</th>
			</tr>
			<tr class="table-tr" v-for="(item,index) in dataList" :key="index">
				<td>{{index+1}}</td>
				<td><img :src="item.publicityPicture" /></td>
				<td>{{getactname(item)}}</td>
				<td>{{getactcode(item)}}</td>
				<td>{{getcupname(item)}}</td>
				<td>{{getcupcode(item)}}</td>
				<td>{{item.updateTm?myGetTime(item.updateTm):myGetTime(item.createTm)}}</td>
				<td style="text-align: center;">
					<gray-button class="grayBtn" :text="'更新'" :clickEvent="clickEdit.bind(this, index,item)"></gray-button>
					<gray-button class="grayBtn" :text="'删除'" :clickEvent="deleteGoods.bind(this, item)"></gray-button>
				</td>
			</tr>
		</table>
		<edit-model ref="editModel" title="优惠券">
			<div class="slot-notice food" style="text-align: left;" slot="main">
				<div>
					<p class="eidt-slot-title">宣传图片<span class="required">*</span></p>
					<div class="upload-box">
						<img-upload :deleteCallback="deleteImgCallback" ref="bannerImg" :imgShowList="getBannerUrl ? [getBannerUrl] : []">
						</img-upload>
					</div>
				</div>
				<div class="textleft">
					<span class="eidt-slot-title" style="width: 50%;">活动选择<span class="required">*</span></span>
					<select class="searchselect" v-model="selected" ref='searchSelect' @change="fnselect()">
						<option v-for="(option,index) in optionGoodsCode" :key="index" :value="option.couponActivityCode">{{option.couponActivityName}}</option>
					</select>
				</div>
				<div class="textleft">
					<span class="eidt-slot-title" style="width: 50%;">优惠券选择<span class="required">*</span></span>
					<select class="searchselect" v-model="selected2" ref='searchSelect2'>
						<option v-for="(option2,index2) in optionGoodsCode2" :key="index2" :value="option2">{{option2.couponName}}</option>
					</select>
				</div>
				<div class="fabu-box" style="text-align: center;">
					<blue-button text="发布" :clickEvent="upLoadImg"></blue-button>
					<!--<gray-button text="取消" :clickEvent="hideModel" class="confimBtn"></gray-button>-->
				</div>
			</div>
		</edit-model>
		<m-toast ref="toast"></m-toast>
		<m-dialog ref="dialog"></m-dialog>
	</div>

</template>

<script>
	import BlueButton from "../../../edit-components/BlueButton";
	import CirleSelect from "../../../edit-components/CirleSelect";
	import getDate from "./getGoodsDate.js";
	import madd from "./add.js";
	import medit from "./edit.js";
	import deleteGoods from './delete.js';
	import GrayButton from "../../../edit-components/GrayButton";
	import EditModel from "../../../edit-components/EditModel";
	import Toast from "../../../edit-components/Toast";
	import Dialog from "../../../edit-components/Dialog";
	import { getPageNameOrVirtualPageName } from "../../../utils/getPageName";
	import imgUpload from "../../../real-components/ImgUpload2";
	import axios from "axios";
	export default {
		props: {
			relGroup: {
				type: String,
				default: ""
			}
		},
		data() {
			return {
				dataList: [],
				uploadType: '',
				couponActivityName: '', //活动名称
				couponName: '', //优惠券名称
				editItem: null,
				storeCode: "",
				SelectedStatedata: [{
					index: 0,
					text: "一行一列"
				}, {
					index: 1,
					text: "一行两列"
				}, {
					index: 2,
					text: "一行三列"
				}],
				activeIndex: 0,
				//图片
				imgUrl: '',
				getBannerUrl: null,
				//活动的下拉选择
				selected: '',
				optionGoodsCode: [],
				selectName:'',
				//优惠券的下拉选择
				selected2: {},
				optionGoodsCode2: [],
			}
		},
		components: {
			"blue-button": BlueButton,
			"cirle-select": CirleSelect,
			"gray-button": GrayButton,
			"edit-model": EditModel,
			"m-toast": Toast,
			"m-dialog": Dialog,
			"img-upload": imgUpload,
		},
		computed: {
			myDateList() {
				return this.dataList;
			},
			pageName() {
				return getPageNameOrVirtualPageName();
			},
		},
		watch: {
			relGroup(newVal) {
				this.getDateList();
				this.getactivities()
				this.getShopCode();
			},
			/*selected(data){
				if(data){
					this.optionGoodsCode2 = data.couponList;
				}
			}*/
		},
		methods: {
			//改变活动选中的值
			fnselect() {
				this.selected = this.$refs.searchSelect.value
				console.log('1111111111', this.selected)
				for(var i = 0; i < this.optionGoodsCode.length; i++) {
					if(this.optionGoodsCode[i].couponActivityCode == this.selected) {
						this.optionGoodsCode2 = this.optionGoodsCode[i].couponList
						this.selectName = this.optionGoodsCode[i].couponActivityName
						break
					}
				}
			},
			//获取门店code
			getShopCode() {
				this.storeCode = localStorage.getItem("storeCode");
			},
			//获取优惠券活动信息
			getactivities() {
				let url = api.trade_host + '/marketCenter/onlineCouponActivityList/' + api.enterpriseCode;
				let config = {
					url: url,
					method: 'GET',
					headers: {
						'sessionId': localStorage.getItem('sessionId'),
					},
				};
				axios(config).then((res) => {
					this.optionGoodsCode = res.data.data;
				})
			},
			/*获取商品编码*/
			showMenu() {
				this.$refs.editModel.showSlideMenu();
				this.$refs.searchModel.hideModel();
			},
			errorToast(msg, duration = 1000) {
				this.$refs.toast.toast(msg, duration);
			},
			//数据渲染
			getDateList() {
				let callback = (data) => {
					this.dataList = data;
				}
				getDate(callback, this.relGroup);
			},
			//活动名称
			getactname(item) {
				return JSON.parse(item.extendField).activitiename
			},
			//活动编码
			getactcode(item) {
				return JSON.parse(item.extendField).activitie //JSON.parse(JSON.parse(item.extendField).activitie).couponActivityName //JSON.parse(item.extendField).activitie.couponActivityName
			},
			//优惠券名称
			getcupname(item) {
				return JSON.parse(item.extendField).coupons.couponName
			},
			//优惠券券码
			getcupcode(item) {
				return JSON.parse(item.extendField).coupons.couponCode
			},
			//处理活动部分数据
			actsortdata(val) {
				return {
					couponActivityName: val.couponActivityName, //活动名称
					couponActivityCode: val.couponActivityCode, //活动编码
					couponActivityId: val.couponActivityId, //活动id
					endTime: val.endTime, //活动结束时间
					startTime: val.startTime, //活动开始时间
					couponVOList: val.couponList, //活动下的优惠券
				}
			},
			//处理优惠券部分数据
			cupsortdata(val) {
				return {
					usePlatform: val.usePlatform, //使用平台
					couponName: val.couponName, //优惠券名称
					useRange: val.useRange, //优惠券使用范围
					preferentialRange: val.preferentialRange, //优惠券使用范围明细
					fullElement: val.fullElement, //优惠限制满多少减
					couponAmount: val.couponAmount, //满减
					couponDiscount: val.couponDiscount, //满折
					endTime: val.availableEndTime, //优惠券结束时间
					startTime: val.availableStartTime, //优惠券开始时间
					couponsCode: val.couponCode, //优惠券编码
					auditorStatus: val.auditorStatus, //活动状态
				}
			},
			//时间转换
			myGetTime(param) {
				if(param) {
					let date = new Date(param);
					let year = date.getFullYear();
					let month = checkTime(date.getMonth() + 1);
					let day = checkTime(date.getDate());
					let hour = date.getHours();
					let min = checkTime(date.getMinutes());
					let sec = checkTime(date.getSeconds());
					let str = '';
					let mHour = 0;
					if(0 < Number(hour) && Number(hour) < 12) {
						mHour = hour;
						str = '上午'
					} else {
						mHour = Number(hour) - 12;
						str = '下午'
					}

					function checkTime(i) {
						if(i < 10) {
							i = '0' + i;
						}
						return i;
					}
					return year + '/' + month + '/' + day + '  ' + str + ' ' + mHour + ':' + min;
				} else {
					return '';
				}
			},
			showModel() {
				this.$refs.editModel.showCover();
			},
			hideModel() {
				this.$refs.editModel.hideCover();
			},
			getParams() {
				var alldata = {
					activitiename:this.selectName,
					activitie: this.selected,
					coupons: this.selected2
				}
				if(this.uploadType == 'add') {
					var params = {
						publicityPicture: this.imgUrl,
						storeCode: this.storeCode,
						relGroup: this.relGroup,
						extendField: JSON.stringify(alldata)
					}
				} else if(this.uploadType == 'edit') {
					var params = {
						publicityPicture: this.imgUrl,
						storeCode: this.storeCode,
						rid: this.editItem.rid,
						relGroup: this.relGroup,
						extendField: JSON.stringify(alldata)
					}
				}
				return params;
			},
			add() {
				let params = this.getParams();
				let callback = data => {
					this.dataList = data;
					this.$refs.editModel.hideCover();
				}
				madd(params, this.relGroup, callback);
			},
			edit() {
				let params = this.getParams();
				let callback = data => {
					this.dataList = data;
					this.$refs.editModel.hideCover();
				}
				medit(params, this.relGroup, callback);
			},
			clickAdd() {
				this.showModel();
				this.uploadType = 'add';
				this.$refs.bannerImg.deleteImg();
				this.selected = '';
				this.selectName = '';
				this.selected2 = {};
				this.optionGoodsCode2 = [];
				this.imgUrl = '';
				this.getBannerUrl = '';
			},
			clickEdit(index, item) {
				this.uploadType = 'edit';
				this.editItem = item;
				this.showModel();
				this.getBannerUrl = item.publicityPicture;
				this.imgUrl = item.publicityPicture;
				this.selected = JSON.parse(item.extendField).activitie
				this.selectName = JSON.parse(item.extendField).activitiename
				var arrcode = []
				for(var i = 0; i < this.optionGoodsCode.length; i++) {
					if(this.optionGoodsCode[i].couponActivityCode == this.selected) {
						this.optionGoodsCode2 = this.optionGoodsCode[i].couponList
						break
					}else{
						arrcode.push(this.optionGoodsCode[i].couponActivityCode)
					}
				}
				if(arrcode.length == this.optionGoodsCode.length){
					this.selected2 = ''
					this.errorToast("该优惠券活动已结束",2000)
					return
				}
				for(var j=0;j<this.optionGoodsCode2.length;j++){
					if(this.optionGoodsCode2[j].couponCode == JSON.parse(item.extendField).coupons.couponCode){
						this.selected2 = this.optionGoodsCode2[j]
						break
					}
				}
				//this.optionGoodsCode2 = JSON.parse(this.selected).couponList //JSON.parse(item.extendField).activitie.couponVOList
				//this.selected2 = JSON.parse(item.extendField).coupons
			},
			deleteGoods(item) {
				console.log(item, 'aa');
				let msg = '确定要删除吗？';
				let confirmFn = () => {
					let params = {
						rid: item.rid,
						storeCode: this.storeCode,
						relGroup: this.relGroup
					}
					let callback = data => {
						this.dataList = data;
					}
					deleteGoods(params, this.relGroup, callback);
				}

				this.infoDialog(msg, confirmFn);

			},
			infoDialog(msg, confirmFn) {
				this.$refs.dialog.dialog({
					msg,
					confirmFn
				});
			},
			async upLoadImg() {
				if(!this.selected) {
					this.errorToast("请选择活动");
					return;
				} else if(!this.$refs.searchSelect2.value) {
					this.errorToast("请选择优惠券");
					return;
				}
				for(var i=0;i<this.dataList.length;i++){
					if(this.uploadType == 'add' && this.selected2.couponCode ==JSON.parse(this.dataList[i].extendField).coupons.couponCode){
						this.errorToast("请不要重复选择优惠券")
						return
					}else if(this.uploadType == 'edit' && this.selected2.couponCode != JSON.parse(this.editItem.extendField).coupons.couponCode && this.selected2.couponCode ==JSON.parse(this.dataList[i].extendField).coupons.couponCode){
						this.errorToast("请不要重复选择优惠券")
						return
					}
				}
				let response = await this.$refs.bannerImg.upload();
				if(response.status === 0) {
					this.errorToast("图片上传失败");
					return;
				}
				if(this.uploadType == 'add') {
					if(response.status === 1) {
						this.imgUrl = response.data[0];
						this.add();
					} else if(response.status === 2) {
						this.errorToast("暂未上传图片");
						return;
					}
				} else {
					if(response.status === 1) {
						this.imgUrl = response.data[0];
						this.edit();
					} else if(response.status === 2) {
						if(!this.imgUrl) {
							this.errorToast("请上传图片");
							return;
						} else {
							this.edit();
						}
					}
				}
			},
			deleteImgCallback() {
				this.imgUrl = '';
			},
			CirleSelectedState(index) {
				this.activeIndex = index;
				this.setEditConfig(this.relGroup, {
					couponsStyle2: this.activeIndex + ""
				}, this.pageName);
			},
			echo() {
				if(this.getCurrentVDO(this.relGroup, this.pageName).config.couponsStyle2 === undefined) {
					this.setEditConfig(this.relGroup, {
						couponsStyle2: this.activeIndex + ""
					}, this.pageName)
				} else {
					this.activeIndex = this.getCurrentVDO(this.relGroup, this.pageName).config.couponsStyle2;
				}
			},
		},
		created() {
			this.getDateList();
			this.getactivities();
			this.getShopCode();
		},
		mounted() {
			this.$nextTick(() => {
				this.echo();
			})
		},
		watch: {
			relGroup() {
				this.getDateList();
				this.getactivities();
				this.getShopCode();
				this.echo();
			}
		}
	}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
	.searchselect {
		display: inline-block;
		border: 1px solid #ddd;
		padding: 5px 5px;
		width: 70%;
		height: unset;
		/* margin-bottom: 15px; */
	}
	
	.confimBtn {
		margin-left: 20px;
	}
	
	.grayBtn {
		display: inline-block;
	}
	
	.fabu-box {
		display: flex;
		justify-content: center;
		margin-top: 30px;
	}
	
	.textleft {
		margin-top: 0.4rem;
	}
	/*新样式*/
	
	.Coupons2 .bannerstyle {
		text-align: left;
		margin-top: 10px;
		margin-bottom: 15px;
	}
	
	.Coupons2 .bannerstyle span {
		display: inline-block;
		width: 120px;
	}
	
	.Coupons2 .bannerstyle .stylename {
		display: inline-block;
		vertical-align: middle;
		margin: 0px 15px;
	}
	
	.bannerstyle {
		text-align: left;
		margin-top: 25px;
	}
	
	.bannerstyle .stylename {
		display: inline-block;
		vertical-align: middle;
		margin: 0px 15px;
	}
	
	.bannerstyle .banneranim {
		display: inline-block;
		margin-right: 15px;
	}
	
	.Coupons2 tr td:nth-child(2) {
		width: 80px;
		display: inline-block;
		height: 66px;
		overflow: hidden;
		line-height: 66px;
		border: none
	}
	
	.Coupons2 tr td:nth-child(2) img {
		height: 66px;
	}
</style>